import {UIElement, UIPanel} from "../../js/threejs/libs/ui.js";
import DeviceToolLabelDialog from "./Device.Tool.Label.Dialog.js";

export default class DeviceToolLabel {
  #labelListDom
  #dropdownClose
  #dropdownOpen
  #signals
  #selectDialog;

  constructor(displayer) {
    let scope = this
    this.#signals = displayer.signals;

    // 下拉列表-设备标签
    let labelRoot = new UIPanel()
    labelRoot.dom.title = '设备标签'
    labelRoot.setClass('label-root')
    labelRoot.setCursor('pointer')

    let labelContent = new UIPanel()
    labelContent.setClass('content')
    labelContent.setTextContent("设备标签")
    labelRoot.add(labelContent)

    let arrowBtn = new UIPanel()
    arrowBtn.setClass('to-down')
    labelRoot.add(arrowBtn)

    /* 下拉菜单展开 */
    let dropdown = new UIPanel()
    dropdown.setClass("dropdown")
    dropdown.setStyle('display', ['none'])
    labelRoot.add(dropdown)

    const dropdownOpen = this.#dropdownOpen = () => {
      arrowBtn.setClass('to-up')
      dropdown.setStyle('display', ['block'])
    }
    const dropdownClose = this.#dropdownClose = () => {
      arrowBtn.setClass('to-down')
      dropdown.setStyle('display', ['none'])
    }

    labelRoot.dom.addEventListener("mousedown", (e) => {
      arrowBtn.dom.className === 'to-down' ? dropdownOpen() : dropdownClose()
    })

    let arrow = new UIPanel()
    arrow.setClass("arrow")
    dropdown.add(arrow)

    let labelListDom = document.createElement("ul")
    this.#labelListDom = labelListDom
    let labelList = new UIElement(labelListDom)
    dropdown.add(labelList)

    /* 右键菜单点击显示标签 */
    this.#signals.deviceMenued.add((object) => {
      /* 显示菜单时关闭标签下拉菜单 */
      dropdownClose()
      if (object !== null) {
        scope.buildLabelList(object)
      }
    })

    /* 直接点击设备时，显示标签 */
    this.#signals.onclick.add((object) => {
      if (object) {
        scope.filterClickLabel(object, 'onclick')
      } else {
        scope.selectLabelClose()
      }
    })

    /* 双击设备时，显示标签 */
    this.#signals.ondbclick.add((object) => {
      if (object) {
        scope.filterClickLabel(object, 'ondbclick')
      } else {
        scope.selectLabelClose()
      }
    })

    this.#signals.objectConfiged.add((object) => {
      if (object) {
        scope.filterClickLabel(object, 'onload')
      } else {
        scope.selectLabelClose()
      }
    })

    this.#signals.cameraChanged.add(function () {
      if (scope.#selectDialog) {
        scope.#selectDialog.dom.remove()
      }
    })

    return labelRoot
  }

  selectLabelClose = () => {
    const dialogs = document.getElementsByClassName('label-select-dialog');
    while (dialogs.length) {
      console.log('删除标签选择框：', dialogs[0])
      dialogs[0].remove()
    }
  }

  /**
   * <p>标签选择框</p>
   * @description 鼠标点击时，有多个标签是列表选择
   * @param object
   * @param labels
   */
  selectLabel = (object, labels) => {
    const scope = this
    const selectDialogId = 'label-select-dialog_' + object.uuid
    if (document.getElementById(selectDialogId)) return

    let selectDialog = new UIPanel()
    selectDialog.setId(selectDialogId)
    selectDialog.setClass("dialog label-select-dialog")
    let ul = new UIElement(document.createElement('ul'))
    selectDialog.add(ul)
    let p = displayer.transPosition(object.position)
    selectDialog.setStyle('left', [p.x + 'px'])
    selectDialog.setStyle('top', [p.y + 'px'])
    let viewport = document.getElementById('viewport')
    viewport.appendChild(selectDialog.dom)
    this.#selectDialog = selectDialog

    for (const label of labels) {
      let a = document.createElement('a')
      a.href = `javascript:;`
      a.innerHTML = label.title
      a.addEventListener('click', () => scope.openDialog(label, object.position))
      let li = document.createElement('li')
      li.appendChild(a)
      ul.dom.appendChild(li)
    }
  }

  /**
   * 过滤点击标签
   * @description 有一个标签时，直接打开，多个时开启选择框
   * @param object
   * @param defaultTrigger
   */
  filterClickLabel = (object, defaultTrigger) => {
    const scope = this
    /* 排除整体场景、灯光对象 */
    if (object && (object.userData.type === 'scene' || object.type.indexOf('Light') > -1)) return
    this.getLabelList(object.uuid, defaultTrigger).then((labels) => {
      if (labels.length > 0) {
        if (labels.length === 1) {
          // 显示label
          scope.openDialog(labels[0], object.position)
        } else {
          scope.selectLabel(object, labels)
        }
      }
    })
  }

  /**
   * 获取后台标签配置
   * @param objectId 设备id（实例id）
   * @param defaultTrigger
   * @returns {Promise}
   */
  getLabelList = (objectId, defaultTrigger = null) => {
    return new Promise((resolve, reject) => {
      displayer.request.getAction('/display/getDeviceLabelConfig', {
        instanceId: objectId,
        defaultTrigger: defaultTrigger
      }).then((data) => {
        if (data.success) {
          resolve(data.result)
        } else {
          resolve(data.message)
        }
      }).catch((error) => {
        reject(error)
      })
    })
  }

  /**
   * 建立标签列表
   * @param object
   */
  buildLabelList = (object) => {
    const scope = this
    this.#labelListDom.innerHTML = ''
    /* 调取所有可用标签配置 */
    this.getLabelList(object.uuid).then(labels => labels.map((label) => {
      let li = document.createElement('li')
      let a = document.createElement('a')
      a.href = `javascript:;`
      a.innerHTML = label.title
      a.addEventListener('mousedown', function (e) {
        scope.#signals.deviceMenued.dispatch(null)
        scope.openDialog(label, object.position)
        scope.#dropdownClose()
      })
      li.appendChild(a)
      this.#labelListDom.appendChild(li)
    }))
  }

  /**
   * 打开标签框
   * @param label 标签配置
   * @param position 位置
   */
  openDialog(label, position) {
    let labelDialog = new DeviceToolLabelDialog(displayer)
    displayer.labelObjects.push(labelDialog)
    labelDialog.createLabelDialog(label, position)
    if (this.#selectDialog) {
      this.#selectDialog.dom.remove()
    }
  }
}